package io.nio.groupchat;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * 群聊客户端
 *
 * @author Verlet
 * @date 2023-01-08 19:16
 */
@Slf4j
public class GroupChatClient {

    private SocketChannel sc;

    private final ByteBuffer readBuf = ByteBuffer.allocate(1024 * 4);
    private final ByteBuffer writeBuf = ByteBuffer.allocate(1024 * 4);

    public GroupChatClient(String hostname, Integer port) {
        InetSocketAddress inetSocketAddress = new InetSocketAddress(hostname, port);
        try {
            sc = SocketChannel.open();
            sc.connect(inetSocketAddress);
            log.info("{} 连接上服务器。。。", sc.getLocalAddress());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void sendMessage() {
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in))) {
            while (sc != null) {
                System.out.print(">> ");
                writeBuf.clear();
                String msg = bufferedReader.readLine();
                if (StringUtils.isBlank(msg)) {
                    continue;
                }
                writeBuf.put(msg.getBytes());
                writeBuf.flip();
                sc.write(writeBuf);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sc != null) {
                try {
                    sc.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public void getMsg() {
        try {
            while (sc != null) {
                readBuf.clear();
                int count = sc.read(readBuf);
                if (count > 0) {
                    readBuf.flip();
                    byte[] bytes = new byte[this.readBuf.remaining()];
                    this.readBuf.get(bytes);
                    String body = new String(bytes);
                    String hostname = body.split("==>")[0].trim();
                    String msg = body.split("==>")[1].trim();
                    System.out.print("\b\b\b");
                    log.info(" {} 发送的数据 ==> {}", hostname, msg);
                    System.out.print(">> ");
                }
                // 1s的延迟
                Thread.sleep(1000);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }


    public static void main(String[] args) {
        log.info("==========欢迎使用群聊系统V1.0，本系统支持单聊功能(@127.0.0.1:port msg)==========");
        GroupChatClient groupChatClient = new GroupChatClient("127.0.0.1", 6728);
        new Thread(groupChatClient::getMsg).start();
        groupChatClient.sendMessage();
    }

}
